<script setup>
  import tabbarData from "@/assets/data/tabbar";
  import {getAssetURL} from "@/utils/loadAssets";
  import {ref, watch} from "vue";
  import {useRoute} from "vue-router";

  const route = useRoute()

  let selectKey = ref(0)

  //监听路由变化并匹配对应的selectKey
  watch(route, newRoute => {
    const index = tabbarData.findIndex(item => item.path === newRoute.path)

    //匹配不到的话直接返回
    if (index === -1) return
    selectKey.value = index
  })

</script>

<template>
  <div class="tabBar">

    <van-tabbar v-model="selectKey" route>
      <template v-for="(item,index) in tabbarData" :key="index">
        <van-tabbar-item :to="item.path">

          <template #icon>
            <img v-if="selectKey !== index" :src="getAssetURL(item.image)" :alt="item.text">
            <img v-else :src="getAssetURL(item.imageActive)" :alt="item.text">
          </template>

          <span>{{ item.text }}</span>
        </van-tabbar-item>
      </template>
    </van-tabbar>

  </div>
</template>

<style lang="less" scoped>
  .tabBar {
    //局部修改ui库的变量（只针对.tarBar的子元素才生效），如果放到 common.css 则是全局修改变量
    //--van-tabbar-item-font-size: 12px;
    --van-tabbar-item-icon-margin-bottom: 2px;
    --van-tabbar-item-active-color: var(--primary-color);

    //找到类，对类中的css重写
    //如果不生效的话是因为 scoped 作用域的原因
    //.van-tabbar-item {
    //  font-size: 12px;
    //}

    //:deep()可以让当前组件以及子组件的类生效
    :deep(.van-tabbar-item) {
      font-size: 12px;
    }

    img {
      height: 25px;
    }
  }
</style>